package com.yzkj.siot.util;

import java.io.File;
import java.util.List;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.FileSystemResource;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;

/**
 * 邮件发送工具类
 * 
 * @author Skye
 *
 */
@Component
public class EmailHelper {

	@Autowired
	private JavaMailSender mailSender;

	@Value("${spring.mail.username}")
	private String from;

	/**
	 * 发送简单文本邮件
	 * 
	 * @param subject   主题
	 * @param contnet   内容
	 * @param filePaths 附件路径列表
	 * @param to        目的地
	 * @throws MessagingException
	 */
	public void sendMail(String subject, String content, List<String> filePaths, Boolean html, String... to)
			throws MessagingException {

		MimeMessage message = mailSender.createMimeMessage();

		MimeMessageHelper helper = new MimeMessageHelper(message, true);
		helper.setTo(to);
		helper.setSubject(subject);
		helper.setText(content, html);
		helper.setFrom(from.trim());
		if (filePaths != null && filePaths.size() > 0) {
			for (String filePath : filePaths) {
				FileSystemResource file = new FileSystemResource(new File(filePath));
				String fileName = file.getFilename();
				helper.addAttachment(fileName, file);
			}
		}

		mailSender.send(message);
	}

	/**
	 * 发送html邮件
	 * 
	 * @param subject 主题
	 * @param contnet 内容
	 * @param to      目的地
	 * @throws MessagingException
	 */
	public void sendHtmlEmail(String subject, String content, String... to) throws MessagingException {

		this.sendMail(subject, content, null, true, to);

	}

	/**
	 * 发送简单文本邮件
	 * 
	 * @param subject 主题
	 * @param contnet 内容
	 * @param to      目的地
	 * @throws MessagingException
	 */
	public void sendTextMail(String subject, String contnet, String... to) throws MessagingException {

		this.sendMail(subject, contnet, null, false, to);
	}
}
